package com.aboo.infrastructure.redis.action;

import com.aboo.infrastructure.base.domain.dto.Result;
import com.aboo.infrastructure.redis.po.ApiVo;
import com.aboo.infrastructure.redis.po.Cell;
import com.aboo.infrastructure.redis.service.RedisService;
import com.aboo.infrastructure.redis.frame.util.DistributedLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisAction {

    @Resource
    private RedisService redisService;
    @Resource
    private DistributedLockUtil distributedLockUtil;

    @PostMapping(value = "/api")
    public Result<Void> api(@RequestBody ApiVo apiVo) {
        boolean limit = redisService.limit(apiVo.getUserId(), apiVo.getMethod());
        if (limit) {
            return Result.error();
        }

        return Result.success();
    }

    @RequestMapping("/getSetRedisStr")
    public Result<String> getSetRedisStr() {
        String data = redisService.getSetRedisStr();

        log.info("String in Redis: {}", (data == null ? "null" : data));
        return Result.success(data);
    }

    @RequestMapping("/getSetRedisObj")
    public Result<Cell> getSetRedisObj() {
        Cell data = redisService.getSetRedisObj();

        log.info("Object in Redis: {}", (data == null ? "null" : data.toString()));
        return Result.success(data);
    }

    @RequestMapping("/incrRedis")
    public Result<Object> incrRedis() {
        String data = redisService.incrRedis();

        log.info(data);
        return Result.success(data);
    }

    @PostMapping("/distributedLock")
    public Result<Void> distributedLock() {
        String key = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
        boolean rt1 = distributedLockUtil.tryGetDistributedLock(key, "845", 1);
        boolean rt2 = distributedLockUtil.tryGetDistributedLock(key, "846", 1);
        boolean rt3 = distributedLockUtil.tryGetDistributedLock(key, "847", 1);
        boolean rt4 = distributedLockUtil.releaseDistributedLock(key, "845");
        boolean rt5 = distributedLockUtil.releaseDistributedLock(key, "846");
        boolean rt6 = distributedLockUtil.releaseDistributedLock(key, "847");
        boolean rt7 = distributedLockUtil.tryGetDistributedLock(key, "848", 1);
        boolean rt8 = distributedLockUtil.releaseDistributedLock(key, "848");
        log.info("rt1:{}, rt2:{}，rt3:{}, rt4:{}，rt5:{}, rt6:{}，rt7:{}, rt8:{}", rt1, rt2, rt3, rt4, rt5, rt6, rt7, rt8);
        return Result.success();
    }

    @RequestMapping("/geo")
    public Result<Void> geo() {
        redisService.geo();

        return Result.success();
    }
}
